package com.fingard.dsp.bank.directbank.abc02;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

import com.fingard.client.DspClient;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ICancelAuthorizeForRec;
import com.fingard.dsp.bank.helpers.FileType;
import com.fingard.dsp.bank.reqrespobj.authcancelforrec.*;
import com.fingard.dsp.bank.reqrespobj.authcancelforrec.detail.RetAtsQryRecAuthCancelInfoDetail;
import com.fingard.dsp.bank.reqrespobj.authforrec.ReqAuthForRec;
import com.fingard.dsp.bank.reqrespobj.authforrec.RetAtsAuthForRec;
import com.fingard.io.FileHelper;
import com.fingard.net.TcpReceiver;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class ABC02AuthrizeCancelForRec extends ABC02Base implements ICancelAuthorizeForRec {
    @Override
    public RetAtsAuthCancelForRec d_AuthCancel(ReqAuthCancelForRec p_req) throws Exception {
        return d_auth_IBBF20(p_req);
    }

    @Override
    public RetAtsQryAuthCancelForRec d_qry_AuthCancel(ReqQryAuthCancelForRec p_req) throws Exception {
        RetAtsQryAuthCancelForRec tmpRetAts = new RetAtsQryAuthCancelForRec(p_req.reqHeader);
        tmpRetAts.respCode = "-1";
        tmpRetAts.respInfo = "暂不支持签约状态查询，请通过签约信息查询核对!";
        if (tmpRetAts.getWriteRdCount() <= 0) {
            tmpRetAts.writeRetHead();
        }
        return tmpRetAts;
    }

    @Override
    public RetAtsQryRecAuthCancelInfo d_qry_AuthCancelInfo(ReqQryRecAuthCancelInfo p_req) throws Exception {
        if (StringHelper.isNullOrEmpty(p_req.oppAct) == false) {
            return d_qry_authInfo_CQRB80(p_req);
        } else {
            return d_qry_authInfo_CQRB79(p_req);
        }
    }

    public RetAtsAuthCancelForRec d_auth_IBBF20(ReqAuthCancelForRec p_req) {
        RetAtsAuthCancelForRec tmpRetAts = new RetAtsAuthCancelForRec(p_req.reqHeader);
        try {
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.CCTransCode = "IBBF20";
            bankHeader.ReqSeqNo = p_req.reqSeqID;

            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeElementString("FileFlag", "1");
            xmlWriter.writeStartElement("Cmp");
            xmlWriter.writeElementString("DbProv", p_req.reqReserved1);//省市代码
            xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req.ownAct));//账号
            xmlWriter.writeElementString("DbCur", convertCurToBank("1"));//币种代码
            xmlWriter.writeElementString("DbLogAccNo", "");//账簿号
            xmlWriter.writeElementString("SumNum", p_req.totalNum);//签约笔数
            String tmpDataFileName = p_req.reqSeqID + ".txt";
            xmlWriter.writeElementString("BatchFileName", tmpDataFileName);//文件名
            xmlWriter.writeEndElement();
            xmlWriter.writeStartElement("Corp");
            xmlWriter.writeElementString("DbAccName", p_req.ownActName);//委托方户名
            String NVoucherType = getBankConfig().getMapValueByKey("nVoucherType" + bankHeader.CCTransCode, p_req.payType);
            xmlWriter.writeElementString("NVoucherType", NVoucherType);
            xmlWriter.writeElementString("NFAccNo", getBankConfig().getMapValueByKey("nFAccNo" + bankHeader.CCTransCode, p_req.ownAct));
            xmlWriter.writeEndElement();
            xmlWriter.writeElementString("Amt", "0");
            xmlWriter.writeEndDocument();

            StringBuilder tmpSbData = new StringBuilder();
            while (p_req.readRecord()) {
                tmpSbData.append(p_req.readedDetail.oppAct + "|_|");
                tmpSbData.append("01|_|");
                tmpSbData.append(p_req.readedDetail.oppActName + "|_|");
                tmpSbData.append(p_req.readedDetail.reqReserved4 + "|_|");
                tmpSbData.append(p_req.readedDetail.certNum + "|_|");
            }
            String tmpFilePath = "";
            if (StringHelper.isNullOrEmpty(bankFront.bkRecFolder)) {
                bankFront.bkRecFolder = bankFront.bkPayFolder;
            }
            tmpFilePath = StringHelper.trimEnd(bankFront.bkRecFolder, File.separator) + File.separator + tmpDataFileName;
            WriteBankLogLn("上传文件地址：" + tmpFilePath);
            StringBuilder smbFileSb = new StringBuilder();
            if (tmpFilePath.startsWith("smb://")) {
                int uploadRet = SmbFileUtil.smbWrite(tmpFilePath, tmpSbData.toString(), getCharset(), smbFileSb);
                if (uploadRet < 0) {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = smbFileSb.toString();
                    tmpRetAts.writeRetToATS();
                    return tmpRetAts;
                }
            } else {
                FileHelper.writeFile(tmpFilePath, tmpSbData);
            }

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    tmpRetAts.respCode = "0";
                    tmpRetAts.reqSeqID = p_req.reqSeqID;
                    tmpRetAts.retCode = tmpRetCode != null && tmpRetCode.equals("0000") ? "2" : "1";
                    if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                        tmpRetAts.retMsg = tmpRetRxtInfo;
                    } else {
                        tmpRetAts.retMsg = tmpRetInfo;
                    }
                } else {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAts.respCode = "-1";
                tmpRetAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        tmpRetAts.writeRetToATS();
        return tmpRetAts;
    }

    public RetAtsQryRecAuthCancelInfo d_qry_authInfo_CQRB79(ReqQryRecAuthCancelInfo p_req) throws Exception {
        RetAtsQryRecAuthCancelInfo tmpRetAts = new RetAtsQryRecAuthCancelInfo(p_req.reqHeader);
        tmpRetAts.ownAct = p_req.ownAct;
        try {
            boolean isContinue = true;
            String contFlag = "";
            String contLast = "";
            String tmpRespCode = "";
            String tmpRespInfo = "";
            while (isContinue && tmpRespCode.length() == 0) {
                ABC02Header bankHeader = new ABC02Header();
                bankHeader.CCTransCode = "CQRB79";
                bankHeader.ReqSeqNo = Format.DateTime17Format.format(new Date());

                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("Cme");
                xmlWriter.writeElementString("ContLast", contLast);//续查条件
                xmlWriter.writeEndElement();
                xmlWriter.writeStartElement("Cmp");
                xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req.ownAct));//账号
                xmlWriter.writeElementString("DbProv", p_req.ownArea);//省市代码
                xmlWriter.writeElementString("DbCur", convertCurToBank(p_req.ownCur));//币种
                xmlWriter.writeElementString("ContFlag", contFlag);//续查标志
                xmlWriter.writeEndElement();
                xmlWriter.writeStartElement("Corp");
                xmlWriter.writeElementString("NFAccNo", getBankConfig().getMapValueByKey("nFAccNo" + bankHeader.CCTransCode, p_req.ownAct));//委托方协议号

                xmlWriter.writeEndDocument();

                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                        String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                        String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                        if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                            contFlag = tmpBkReader.getFirstText("/ap/Cmp/ContFlag");
                            if ("0".equals(contFlag)) {
                                isContinue = false;
                            }
                            contLast = tmpBkReader.getFirstText("/ap/Cme/ContLast");

                            int tmpRecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/Cme/RecordNum"));
                            int tmpFieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/Cme/FieldNum"));
                            if (tmpRecordNum > 0) {
                                String tmpDataMFS = null;
                                String tmpFileFlag = tmpBkReader.getFirstText("/ap/FileFlag");
                                if (tmpFileFlag != null && tmpFileFlag.equals("1")) {
                                    String tmpBatchFileName = tmpBkReader.getFirstText("/ap/Cmp/BatchFileName");
                                    String tmpFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + tmpBatchFileName;
                                    this.WriteBankLogLn("读取前置数据文件：" + tmpFilePath);
                                    if ("dspfileserver".equals(this.bankFront.getAccessBkFileModeLowerCase())) {
                                        WriteBankLogLn("accessBkFileMode：" + bankFront.accessBkFileMode);
                                        DspClient dspClient = new DspClient(bankFront.dspFileServer);
                                        dspClient.charsetName = getCharset();
                                        TcpReceiver tcpRec = dspClient.getFile(FileType.bankFile, tmpFilePath);
                                        if (tcpRec.isCompleted) {
                                            if (tcpRec.isRtnBinaryFile) {
                                                tmpDataMFS = new String(tcpRec.recBytes, tcpRec.contentStartIndex, tcpRec.contentLength, tcpRec.charsetName);
                                            } else {
                                                String errMsg = new String(tcpRec.recBytes, tcpRec.contentStartIndex, tcpRec.contentLength, tcpRec.charsetName);
                                                WriteBankLogLn("从远程DSP（" + bankFront.dspFileServer + "）获取前置文件未完成：" + errMsg);
                                            }
                                        } else {
                                            this.WriteBankLogLn("从远程DSP（" + bankFront.dspFileServer + "）获取前置文件未完成：" + tcpRec.getConnMsg());
                                        }
                                    } else {
                                        tmpDataMFS = FileHelper.readFileText(tmpFilePath, getCharset());
                                    }
                                    if (tmpDataMFS == null) {
                                        this.WriteBankLogLn("读取前置数据文件返回为null，需确认前置文件夹配置和文件是否存在");
                                    } else {
                                        this.WriteBankLogStep3(tmpDataMFS);
                                    }
                                } else {
                                    tmpDataMFS = tmpBkReader.getFirstText("/ap/Cmp/RespPrvData1");//
                                }
                                if (tmpDataMFS != null) {
                                    StringBuilder tmpSbLog = new StringBuilder();
                                    ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(tmpDataMFS, "|", tmpFieldNum, tmpRecordNum, tmpSbLog);
                                    if (tmpSbLog.length() == 0) {
                                        for (int i = 0; i < tmpArrayList.size(); i++) {
                                            //0.金融实体代码1|1.合约号1|2.金融实体代码2|3.合约号2|4.子合约号2|5.合约关系类型码|6.关系开始日期|7.委托方协议号|8.目标方账号|9.业务种类|
                                            String[] tmpEachArr = tmpArrayList.get(i);
                                            RetAtsQryRecAuthCancelInfoDetail tmpDetail = new RetAtsQryRecAuthCancelInfoDetail();
                                            tmpDetail.oppAct = tmpEachArr[8];
                                            tmpDetail.oppActCur = p_req.oppCur;
                                            tmpDetail.oppActName = "";
                                            //tmpDetail.queryTag = p_req.queryTag;
                                            tmpRetAts.writeRetDetail(tmpDetail);

                                        }
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = tmpSbLog.toString();
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "数据为空";
                                }
                            }

                        } else {
                            tmpRespCode = "-1";
                            if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                                tmpRespInfo = tmpRetRxtInfo;
                            } else {
                                tmpRespInfo = tmpRetInfo;
                            }
                        }

                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();

                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                }
            }

            tmpRetAts.respInfo = tmpRespInfo;
            if ("-1".equals(tmpRespCode)) {
                tmpRetAts = new RetAtsQryRecAuthCancelInfo(p_req.reqHeader);
                tmpRetAts.ownAct = p_req.ownAct;
                tmpRetAts.respCode = tmpRespCode;
                tmpRetAts.respInfo = tmpRespInfo;
            } else {
                tmpRetAts.respCode = "0";
            }

        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        tmpRetAts.writeAfterDetail();
        return tmpRetAts;
    }

    public RetAtsQryRecAuthCancelInfo d_qry_authInfo_CQRB80(ReqQryRecAuthCancelInfo p_req) throws Exception {
        RetAtsQryRecAuthCancelInfo tmpRetAts = new RetAtsQryRecAuthCancelInfo(p_req.reqHeader);
        tmpRetAts.ownAct = p_req.ownAct;
        try {
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.ReqSeqNo = p_req.reqHeader.transSeqID;
            bankHeader.CCTransCode = "CQRB80";

            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("Cmp");
            xmlWriter.writeElementString("DbAccNo", getAbcAccNo(p_req.ownAct));//委托方账号
            xmlWriter.writeElementString("DbProv", p_req.ownArea);//委托方省市代码
            xmlWriter.writeElementString("DbCur", convertCurToBank(p_req.ownCur));//委托方币种
            xmlWriter.writeElementString("DbLogAccNo", "");//委托方账簿号
            if ("1".equals(p_req.isPrivate)) {
                xmlWriter.writeElementString("CrAccNo", p_req.oppAct);//目标方账号
                xmlWriter.writeElementString("CrProv", "");//目标方省市代码
            } else {
                xmlWriter.writeElementString("CrAccNo", getAbcAccNo(p_req.oppAct));//目标方账号
                if (p_req.oppAct != null && p_req.oppAct.length() > 2) {
                    xmlWriter.writeElementString("CrProv", p_req.oppAct.substring(0, 2));//目标方省市代码
                } else {
                    xmlWriter.writeElementString("CrProv", p_req.oppArea);//目标方省市代码
                }
            }
            xmlWriter.writeElementString("CrCur", convertCurToBank(p_req.oppCur));//目标方币种
            xmlWriter.writeEndElement();
            xmlWriter.writeStartElement("Corp");
            String NVoucherType = getBankConfig().getMapValueByKey("nVoucherType" + bankHeader.CCTransCode, p_req.reqReserve1);
            xmlWriter.writeElementString("NVoucherType", NVoucherType);//业务类型
            xmlWriter.writeElementString("NFAccNo", getBankConfig().getMapValueByKey("nFAccNo" + bankHeader.CCTransCode, p_req.ownAct));//委托方协议号
            xmlWriter.writeEndElement();
            xmlWriter.writeElementString("qryflag", p_req.isPrivate);//个人对公标志 1-个人、2-对公
            xmlWriter.writeEndDocument();
            tmpRetAts.ownAct = p_req.ownAct;
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                        String tmpConFlag = tmpBkReader.getFirstText("/ap/Cmp/ConFlag");//签约标志 1-已签约、2-未签约
                        tmpRetAts.respCode = "0";
                        if ("1".equals(tmpConFlag)) {
                            RetAtsQryRecAuthCancelInfoDetail tmpDetail = new RetAtsQryRecAuthCancelInfoDetail();
                            tmpDetail.oppAct = p_req.oppAct;
                            tmpDetail.oppActCur = p_req.oppCur;
                            tmpDetail.oppActName = "";
                            tmpDetail.queryTag = p_req.queryTag;
                            tmpRetAts.writeRetDetail(tmpDetail);
                        } else {
                            tmpRetAts.respInfo = "未查询到满足请求条件的签约信息！";
                        }
                    } else {
                        tmpRetAts.respCode = "-1";
                        if (!StringHelper.isNullOrEmpty(tmpRetRxtInfo)) {
                            tmpRetAts.respInfo = tmpRetRxtInfo;
                        } else {
                            tmpRetAts.respInfo = tmpRetInfo;
                        }
                    }
                } else {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAts.respCode = "-1";
                tmpRetAts.respInfo = tmpStrRet[1];
            }

        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        tmpRetAts.writeAfterDetail();
        return tmpRetAts;
    }
}
